package org.gdpu.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.gdpu.Service.DormitoryService;
import org.gdpu.Service.MailboxService;
import org.gdpu.Service.NewsService;
import org.gdpu.Service.UserService;
import org.gdpu.base.PageView;
import org.gdpu.model.Mailbox;
import org.gdpu.model.MailboxState;
import org.gdpu.model.News;
import org.gdpu.model.User;
import org.gdpu.util.ChangeTime;
import org.gdpu.vo.MailboxVO;
import org.gdpu.vo.StudentVO;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by Administrator on 14-3-10.
 */
@Component("mailbox")
@Scope("prototype")
public class MailboxAction extends MyActionSupport implements ModelDriven<MailboxVO> {

    private final MailboxVO mailboxVO = new MailboxVO();
    private NewsService newsService;
    private UserService userService;
    private MailboxService mailboxService;
    private final static Logger logger = LogManager.getLogger(MailboxAction.class);
    //获取当前登录用户
    HttpSession session = ServletActionContext.getRequest().getSession();
    User person = (User) session.getAttribute("person");

    public String sendMail() {
        if (mailboxVO.getStuId().isEmpty()) {
            mailboxVO.setResultMessage("<script>alert('请输入姓名！');location.href='/page/mailboxManagement/sendMail.jsp';</script>");
            return ERROR;
        }
        if (mailboxVO.getMessage().isEmpty()) {
            mailboxVO.setResultMessage("<script>alert('请输入内容！');location.href='/page/mailboxManagement/sendMail.jsp';</script>");
            return ERROR;
        }
        if (mailboxVO.getTitle().isEmpty()) {
            mailboxVO.setResultMessage("<script>alert('请输入主题！');location.href='/page/mailboxManagement/sendMail.jsp';</script>");
            return ERROR;
        }
        if (!"学生宿舍".equals(person.getPowerGroup().getPowerGroup())) {

        }

        // HttpSession session = ServletActionContext.getRequest().getSession();
        if ((String) session.getAttribute("checkTime") == null) {
            session.setAttribute("checkTime", ChangeTime.getCurrentDate());
        } else if (ChangeTime.cha((String) session.getAttribute("checkTime")) > 300)
            session.setAttribute("checkTime", ChangeTime.getCurrentDate());
        else {
            mailboxVO.setResultMessage("<script>alert('请勿连续发送信件！');location.href='/page/mailboxManagement/mailboxIndex.jsp';</script>");
            return ERROR;
        }
        Mailbox mailbox = mailboxService.createMailbox(mailboxVO.getStuId(), mailboxVO.getTitle(), mailboxVO.getMessage());
        if (mailbox == null) {
            mailboxVO.setResultMessage("输入信息有误！");
            return ERROR;
        } else {
            News news = newsService.createNews(mailbox.getStudent(), userService.findByName("宿舍管理部"), "学生提问", "Mailbox!notDealMailList.action?");
            if (news != null)
                newsService.save(news);
            mailboxVO.setResultMessage("<script>alert('信件成功发送！回复结果通过信箱进行通知！');location.href='/page/mailboxManagement/mailboxIndex.jsp';</script>");
            logger.trace("send the mail record success");
            return SUCCESS;
        }
    }

    public String replyMail() {
        if (mailboxVO.getFlag() == 1 || mailboxVO.getReplyMessage().trim().isEmpty()) {
            Mailbox mail = mailboxService.find(Mailbox.class, Integer.valueOf(mailboxVO.getId()));
            mailboxVO.setMailbox(mail);
            view = "/page/mailboxManagement/replyMail.jsp";
            return VIEW;
        } else {
            Mailbox mail = mailboxService.find(Mailbox.class, Integer.valueOf(mailboxVO.getId()));
            mail.setReplyDate(new Date());
            mail.setReplyMessage(mailboxVO.getReplyMessage());
            mail.setMailboxState(MailboxState.DEAL);
            HttpSession session = ServletActionContext.getRequest().getSession();
            User person = (User) session.getAttribute("person");
            mail.setUser(person);
            mailboxService.update(mail);
            News news = newsService.createNews(userService.findByName("宿舍管理部"), mail.getStudent(), "回复提问", "Mailbox!mailList.action?");
            if (news != null)
                newsService.save(news);
            mailboxVO.setResultMessage("<script>alert('信件回复发送！');location.href='Mailbox!notDealMailList.action?newsId';</script>");
            logger.trace("reply success.");
            return SUCCESS;
        }
    }

    public String notDealMailList() {
        if (!mailboxVO.getNewsId().trim().isEmpty()) {
            News news = newsService.find(News.class, Integer.valueOf(mailboxVO.getNewsId()));
            news.setNewsState(MailboxState.DEAL);
            newsService.update(news);
        }

        /** 每页显示的结果数 **/
        int maxResult = 10;
        /** 封装的页面数据 **/
        PageView<Mailbox> pageView = new PageView<Mailbox>(maxResult,
                mailboxVO.getPage());
        int firstIndex = ((pageView.getCurrentPage() - 1) * pageView
                .getMaxResult());// 开始索引

        // 按照条件排序
        LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
        orderBy.put("id", "asc");
        /** 列表条件 **/
        StringBuffer jpql = new StringBuffer("1=1");
        jpql.append(" and o.mailboxState = '0'");
        /** 列表条件的值 **/
        List<Object> params = new ArrayList<Object>();

        pageView.setQueryResult(mailboxService.getScrollData(Mailbox.class, firstIndex, maxResult, jpql.toString(),
                params.toArray(), orderBy));
        mailboxVO.setPageView(pageView);
        view = "/page/mailboxManagement/notDealMailList.jsp";
        return VIEW;
    }

    public String mailList() {
        if (!mailboxVO.getNewsId().trim().isEmpty()) {
            News news = newsService.find(News.class, Integer.valueOf(mailboxVO.getNewsId()));
            news.setNewsState(MailboxState.DEAL);
            newsService.update(news);
        }
        HttpSession session = ServletActionContext.getRequest().getSession();
        User user = (User) session.getAttribute("person");
        List<Mailbox> mxs = mailboxService.findMail("student", user.getDormitory());
        /** 每页显示的结果数 **/
        int maxResult = 10;
        /** 封装的页面数据 **/
        PageView<Mailbox> pageView = new PageView<Mailbox>(maxResult,
                mailboxVO.getPage());
        int firstIndex = ((pageView.getCurrentPage() - 1) * pageView
                .getMaxResult());// 开始索引

        // 按照条件排序
        LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
        orderBy.put("id", "asc");
        /** 列表条件 **/
        StringBuffer jpql = new StringBuffer("1=1");
        jpql.append(" and o.mailboxState = '1'");
        /** 列表条件的值 **/
        List<Object> params = new ArrayList<Object>();

        pageView.setQueryResult(mailboxService.getScrollData(Mailbox.class, firstIndex, maxResult, jpql.toString(),
                params.toArray(), orderBy));

        mailboxVO.setPageView(pageView);
        view = "/page/mailboxManagement/mailList.jsp";
        return VIEW;
    }

    public String deleteMail() {
        mailboxService.deleteMail(mailboxVO.getMailIds());
        mailboxVO.setResultMessage("<script>alert('成功删除信件！');location.href='Mailbox!notDealMailList.action?newsId';</script>");
        logger.trace("delete the mail record success");
        return SUCCESS;
    }

    private void storeTargetToSession(News target) {
        HttpSession session = ServletActionContext.getRequest().getSession();
        News storeTarget = (News) session.getAttribute("news");
        if (storeTarget == null || !storeTarget.equals(target)) {
            session.setAttribute("news", target);
            session.setMaxInactiveInterval(-1);
        }
    }

    public String showMail() {
        Mailbox mailbox = mailboxService.findMail("id", Integer.valueOf(mailboxVO.getId())).get(0);
        mailboxVO.setTitle(mailbox.getTitle());
        mailboxVO.setMessage(mailbox.getMessage());
        mailboxVO.setReplyMessage(mailbox.getReplyMessage());
        logger.error("show the mail record success");
        view = "/page/mailboxManagement/showMail.jsp";
        return VIEW;
    }

    @Resource(name = "mailboxServiceImpl")
    public void setMailboxService(MailboxService mailboxService) {
        this.mailboxService = mailboxService;
    }

    @Resource(name = "newsServiceImpl")
    public void setNewsService(NewsService newsService) {
        this.newsService = newsService;
    }

    @Resource(name = "userServiceImpl")
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public MailboxVO getModel() {
        return mailboxVO;
    }
}
